﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using Microsoft.Win32;
using System.Runtime.InteropServices;

using System.IO.Ports;
using System.Threading;

//using NationalInstruments.LabVIEW.Interop;
//using InteropAssembly;
namespace Ultrasonic
{
    public partial class MainForm : Form
    {

        Socket socket;
        SerialPort boardControlPort = new SerialPort();
        Thread threadReceive;
        public MainForm()
        {
            InitializeComponent();
        }
        //声明读写INI文件的API函数
        [DllImport("kernel32")]
        private static extern bool WritePrivateProfileString(string section, string key, string val, string filePath);
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, byte[] retVal, int size, string filePath);
        static string FileName = Application.StartupPath + "\\Config.ini";
        public string ReadIni(string Section, string Ident, string Default)
        {
            Byte[] Buffer = new Byte[65535];
            int bufLen = GetPrivateProfileString(Section, Ident, Default, Buffer, Buffer.GetUpperBound(0), FileName);
            string s = Encoding.GetEncoding(0).GetString(Buffer);
            s = s.Substring(0, bufLen);
            return s.Trim();
        }

        string CameraIp = "";
        string ControlIp = "192.168.8.1";
        string Port = "2001";
        string CMD_Forward = "", CMD_Backward = "", CMD_TurnLeft = "", CMD_TurnRight = "", CMD_Stop = "", CMD_EngineUp = "", CMD_EngineDown = "", CMD_Engineleft = "", CMD_Engineright = "", CMD_ledon = "", CMD_ledoff = "";
        Int16 MotorAccelerate = 50;
        byte LeftWheelId = 1, RightWheelId = 2;

        private void buttonStop_Click(object sender, EventArgs e)
        {
            try
            {
                UltrasonicGlobal.SetWheelSpeed setSpeedStruct = new UltrasonicGlobal.SetWheelSpeed();
                setSpeedStruct.motor_type = UltrasonicGlobal.SMX_MOTOR_TYPE;
                setSpeedStruct.wheel_id = LeftWheelId;
                setSpeedStruct.speed = 0;
                byte[] sendBytes = BoardCMD.CMD_SET_WHEEL_SPEED_SEND(setSpeedStruct);
                boardControlPort.Write(sendBytes, 0, sendBytes.Length);

                setSpeedStruct.wheel_id = RightWheelId;
                byte[] sendBytes_r = BoardCMD.CMD_SET_WHEEL_SPEED_SEND(setSpeedStruct);
                boardControlPort.Write(sendBytes_r, 0, sendBytes_r.Length);
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }

        /// <summary>
        /// 设置机器人基础的加速转向
        /// </summary>
        /// <param name="left_id"></param>
        /// <param name="acce_left"></param>
        /// <param name="right_id"></param>
        /// <param name="acce_right"></param>
        private void SetRobotAccelerate(byte left_id, Int16 acce_left, byte right_id,  Int16 acce_right)
        {
            try
            {
                UltrasonicGlobal._SetMotorAccelerate setAccelerateStruct = new UltrasonicGlobal._SetMotorAccelerate();
                setAccelerateStruct.motor_type = UltrasonicGlobal.SMX_MOTOR_TYPE;
                setAccelerateStruct.motor_id = left_id;
                setAccelerateStruct.accelerate = acce_left;
                byte[] sendBytes = BoardCMD.CMD_SET_MOTOR_ACCELERATE_SEND(setAccelerateStruct);
                boardControlPort.Write(sendBytes, 0, sendBytes.Length);
                //Thread.Sleep(555);
                setAccelerateStruct.motor_id = right_id;
                setAccelerateStruct.accelerate = acce_right;
                byte[] sendBytes_r = BoardCMD.CMD_SET_MOTOR_ACCELERATE_SEND(setAccelerateStruct);
                boardControlPort.Write(sendBytes_r, 0, sendBytes_r.Length);
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }


        private void Ultrasonic_Load(object sender, EventArgs e)
        {
            GetIni();
            buttonForward.BackColor = Color.LightBlue;
            buttonBackward.BackColor = Color.LightBlue;
            buttonLeft.BackColor = Color.LightBlue;
            buttonRight.BackColor = Color.LightBlue;
            buttonStop.BackColor = Color.LightBlue;
            btnEngineUp.BackColor = Color.LightBlue;
            btnEngineDown.BackColor = Color.LightBlue;
            btnEngineleft.BackColor = Color.LightBlue;
            btnEngineright.BackColor = Color.LightBlue;
            buttonLED.BackColor = Color.LightBlue;
            buttonVideo.BackColor = Color.LightBlue;
        }
        private void GetIni()
        {
            CameraIp = ReadIni("VideoUrl", "videoUrl", "");
            ControlIp = ReadIni("ControlUrl", "controlUrl", "");
            Port = ReadIni("ControlPort", "controlPort", "");
            CMD_Forward = ReadIni("ControlCommand", "CMD_Forward", "");
            CMD_Backward = ReadIni("ControlCommand", "CMD_Backward", "");
            CMD_TurnLeft = ReadIni("ControlCommand", "CMD_TurnLeft", "");
            CMD_TurnRight = ReadIni("ControlCommand", "CMD_TurnRight", "");
            CMD_Stop = ReadIni("ControlCommand", "CMD_Stop", "");
            CMD_EngineUp = ReadIni("ControlCommand", "CMD_EngineUp", "");
            CMD_EngineDown = ReadIni("ControlCommand", "CMD_EngineDown", "");
            CMD_Engineleft = ReadIni("ControlCommand", "CMD_Engineleft", "");
            CMD_Engineright = ReadIni("ControlCommand", "CMD_Engineright", "");
            CMD_ledon = ReadIni("ControlCommand", "CMD_ledon", "");
            CMD_ledoff = ReadIni("ControlCommand", "CMD_ledoff", "");

            string portName = ControlPortInitializeName();
            if (boardControlPort.IsOpen)
            {
                //MessageBox.Show("板卡通信成功");
            }
            else if (portName == "ERROR")
            {
                MessageBox.Show("板卡通信异常，请检查重试");
            }
            else
            {
                if (!boardControlPort.IsOpen)
                {
                    boardControlPort.BaudRate = 9600;
                    boardControlPort.PortName = portName;
                    boardControlPort.ReadTimeout = 800;
                    boardControlPort.Open();
                    threadReceive = new Thread(new ThreadStart(ReceiveData));
                    threadReceive.IsBackground = true;
                    threadReceive.Start();
                }
                //MessageBox.Show("板卡通信成功");
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            pBShow.ImageLocation = CameraIp;// "http://192.168.1.1:8080/?action=snapshot";
        }

        private void buttonVideo_Click(object sender, EventArgs e)
        {
            //timer1.Enabled = true;
            this.thread = new Thread(new ThreadStart(this.ThreadProc));
            this.thread.Start();

        }
        #region 视频显示第二个WiFi模块
        private Thread thread;
        //private PictureBox pBShow;
        //private Label label_fps;
 

        public void ThreadProc()
        {
            this.GetStream(this.CameraIp);
        }
        private void GetStream(string UriString)
        {
            DateTime time;
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            Stream responseStream = null;
            int fps = 0;
            byte[] jpg_buf = new byte[0x80000];
            byte[] buffer = new byte[0x1000];
        Label_0039:
            try
            {
                EventHandler method = null;
                time = DateTime.Now;
                fps = 0;
                request = (HttpWebRequest)WebRequest.Create(UriString);
                response = (HttpWebResponse)request.GetResponse();
                int num2 = 0;
                int jpg_count = 0;
                while (true)
                {
                    responseStream = response.GetResponseStream();
                    int num = responseStream.Read(buffer, 0, 0x1000);
                    if (num > 0)
                    {
                        for (int i = 0; i < num; i++)
                        {
                            switch (num2)
                            {
                                case 0:
                                    {
                                        if (buffer[i] != 0x43)
                                        {
                                            break;
                                        }
                                        num2++;
                                        continue;
                                    }
                                case 1:
                                    {
                                        if (buffer[i] != 0x6f)
                                        {
                                            goto Label_012F;
                                        }
                                        num2++;
                                        continue;
                                    }
                                case 2:
                                    {
                                        if (buffer[i] != 110)
                                        {
                                            goto Label_014A;
                                        }
                                        num2++;
                                        continue;
                                    }
                                case 3:
                                    {
                                        if (buffer[i] != 0x74)
                                        {
                                            goto Label_0165;
                                        }
                                        num2++;
                                        continue;
                                    }
                                case 4:
                                    {
                                        if (buffer[i] != 0x65)
                                        {
                                            goto Label_0180;
                                        }
                                        num2++;
                                        continue;
                                    }
                                case 5:
                                    {
                                        if (buffer[i] != 110)
                                        {
                                            goto Label_019B;
                                        }
                                        num2++;
                                        continue;
                                    }
                                case 6:
                                    {
                                        if (buffer[i] != 0x74)
                                        {
                                            goto Label_01B6;
                                        }
                                        num2++;
                                        continue;
                                    }
                                case 7:
                                    {
                                        if (buffer[i] != 0x2d)
                                        {
                                            goto Label_01D1;
                                        }
                                        num2++;
                                        continue;
                                    }
                                case 8:
                                    {
                                        if (buffer[i] != 0x4c)
                                        {
                                            goto Label_01EC;
                                        }
                                        num2++;
                                        continue;
                                    }
                                case 9:
                                    {
                                        if (buffer[i] != 0x65)
                                        {
                                            goto Label_0207;
                                        }
                                        num2++;
                                        continue;
                                    }
                                case 10:
                                    {
                                        if (buffer[i] != 110)
                                        {
                                            goto Label_0222;
                                        }
                                        num2++;
                                        continue;
                                    }
                                case 11:
                                    {
                                        if (buffer[i] != 0x67)
                                        {
                                            goto Label_023D;
                                        }
                                        num2++;
                                        continue;
                                    }
                                case 12:
                                    {
                                        if (buffer[i] != 0x74)
                                        {
                                            goto Label_0258;
                                        }
                                        num2++;
                                        continue;
                                    }
                                case 13:
                                    {
                                        if (buffer[i] != 0x68)
                                        {
                                            goto Label_0273;
                                        }
                                        num2++;
                                        continue;
                                    }
                                case 14:
                                    {
                                        if (buffer[i] != 0x3a)
                                        {
                                            goto Label_028E;
                                        }
                                        num2++;
                                        continue;
                                    }
                                case 15:
                                    {
                                        if (buffer[i] == 0xff)
                                        {
                                            num2++;
                                        }
                                        jpg_count = 0;
                                        jpg_buf[jpg_count++] = buffer[i];
                                        continue;
                                    }
                                case 0x10:
                                    {
                                        if (buffer[i] != 0xd8)
                                        {
                                            goto Label_030A;
                                        }
                                        num2++;
                                        jpg_buf[jpg_count++] = buffer[i];
                                        continue;
                                    }
                                case 0x11:
                                    {
                                        jpg_buf[jpg_count++] = buffer[i];
                                        if (buffer[i] == 0xff)
                                        {
                                            num2++;
                                        }
                                        if (jpg_count >= 0x80000)
                                        {
                                            num2 = 0;
                                        }
                                        continue;
                                    }
                                case 0x12:
                                    {
                                        jpg_buf[jpg_count++] = buffer[i];
                                        if (buffer[i] != 0xd9)
                                        {
                                            goto Label_03B1;
                                        }
                                        num2 = 0;
                                        if (method == null)
                                        {
                                            method = delegate(object param0, EventArgs param1)
                                            {
                                                fps++;
                                                Image image = this.byteArrayToImage(jpg_buf, jpg_count);
                                                this.pBShow.Image = image;
                                                if (DateTime.Now >= time.AddSeconds(1.0))
                                                {
                                                    this.label_fps.Text = fps.ToString() + " fps";
                                                    fps = 0;
                                                    time = DateTime.Now;
                                                }
                                            };
                                        }
                                        base.Invoke(method);
                                        continue;
                                    }
                                default:
                                    goto Label_03C2;
                            }
                            num2 = 0;
                            continue;
                        Label_012F:
                            num2 = 0;
                            continue;
                        Label_014A:
                            num2 = 0;
                            continue;
                        Label_0165:
                            num2 = 0;
                            continue;
                        Label_0180:
                            num2 = 0;
                            continue;
                        Label_019B:
                            num2 = 0;
                            continue;
                        Label_01B6:
                            num2 = 0;
                            continue;
                        Label_01D1:
                            num2 = 0;
                            continue;
                        Label_01EC:
                            num2 = 0;
                            continue;
                        Label_0207:
                            num2 = 0;
                            continue;
                        Label_0222:
                            num2 = 0;
                            continue;
                        Label_023D:
                            num2 = 0;
                            continue;
                        Label_0258:
                            num2 = 0;
                            continue;
                        Label_0273:
                            num2 = 0;
                            continue;
                        Label_028E:
                            num2 = 0;
                            continue;
                        Label_030A:
                            if (buffer[i] != 0xff)
                            {
                                num2 = 15;
                            }
                            continue;
                        Label_03B1:
                            if (buffer[i] != 0xff)
                            {
                                num2 = 0x11;
                            }
                            continue;
                        Label_03C2:
                            num2 = 0;
                        }
                    }
                }
            }
            catch (Exception)
            {
                if (request != null)
                {
                    request.Abort();
                    request = null;
                }
                if (response != null)
                {
                    response.Close();
                    response = null;
                }
                if (responseStream != null)
                {
                    responseStream.Close();
                    responseStream = null;
                }
                goto Label_0039;
            }
        }
        private Image byteArrayToImage(byte[] Bytes, int count)
        {
            using (MemoryStream stream = new MemoryStream(Bytes, 0, count))
            {
                return Image.FromStream(stream);
            }
        }

 

 

        #endregion



        void SendData(string data)
        {
            try
            {
                //IPAddress ips = IPAddress.Parse(ControlIp.ToString());//("192.168.2.1");
                //IPEndPoint ipe = new IPEndPoint(ips, Convert.ToInt32(Port.ToString()));//把ip和端口转化为IPEndPoint实例
                //Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket

                //c.Connect(ipe);//连接到服务器

                byte[] bs = Encoding.ASCII.GetBytes(data);

                socket.Send(bs, bs.Length, 0);//发送测试信息
                byte[] buffer = new byte[1111];
                //c.Receive(buffer);
                MessageBox.Show(socket.Available.ToString());
                //c.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
        /// <summary> Send the user's data currently entered in the 'send' box.</summary>
        private void SendData()
        {
            //if (CurrentDataMode == DataMode.Text)
            //{
            //    // Send the user's text straight out the port
            //    SocketSend(txtSendData.Text);

            //    // Show in the terminal window the user's text
            //    Log(LogMsgType.Outgoing, txtSendData.Text + "\n");
            //}
            //else
            //{
                try
                {
                    // Convert the user's string of hex digits (ex: B4 CA E2) to a byte array
                    //byte[] data = HexStringToByteArray(txtSendData.Text);

                    // Send the binary data out the port
                    //SocketSend(data);

                    // Show the hex digits on in the terminal window
                    //Log(LogMsgType.Outgoing, ByteArrayToHexString(data) + "\n");
                }
                catch (FormatException)
                {
                    // Inform the user if the hex string was not properly formatted
                    //Log(LogMsgType.Error, "Not properly formatted hex string: " + txtSendData.Text + "\n");
                }
            //}
            //txtSendData.SelectAll();
        }
    #region Socket
    //向Telnet服务器发送命令
    private void SocketSend(string msg)
        {
            System.Byte[] message = System.Text.Encoding.ASCII.GetBytes(msg.ToCharArray());
            socket.Send(message, message.Length, 0);
        }

        //向Telnet服务器发送命令
        private void SocketSend(char[] chr)
        {
            System.Byte[] message = System.Text.Encoding.ASCII.GetBytes(chr);
            socket.Send(message, message.Length, 0);
        }

        //向Telnet服务器发送数据
        private void SocketSend(byte[] data)
        {
            try
            {
                System.Byte[] message = data;
                socket.Send(message, message.Length, 0);
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }

        //接收数据
        private string Receive()
        {
            //用于接收数据的缓冲
            byte[] buf;
            string result = "";

            int count = socket.Available;
            if (count > 0)
            {
                buf = new byte[count];
                socket.Receive(buf);
                    result = ByteArrayToHexString(buf);
                    //result = ProcessOptions(buf);
            }

            return result;
        }
        #endregion
        /// <summary> Convert a string of hex digits (ex: E4 CA B2) to a byte array. </summary>
        /// <param name="s"> The string containing the hex digits (with or without spaces). </param>
        /// <returns> Returns an array of bytes. </returns>
        private byte[] HexStringToByteArray(string s)
        {
            s = s.Replace(" ", "");
            byte[] buffer = new byte[s.Length / 2];
            for (int i = 0; i < s.Length; i += 2)
            {
                buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
            }

            return buffer;
        }

        /// <summary> Converts an array of bytes into a formatted string of hex digits (ex: E4 CA B2)</summary>
        /// <param name="data"> The array of bytes to be translated into a string of hex digits. </param>
        /// <returns> Returns a well formatted string of hex digits with spacing. </returns>
        private string ByteArrayToHexString(byte[] data)
        {
            StringBuilder sb = new StringBuilder(data.Length * 3);
            foreach (byte b in data)
            {
                sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));
            }

            return sb.ToString().ToUpper();
        }
        private void Ultrasonic_FormClosed(object sender, FormClosedEventArgs e)
        {
            if(socket!=null)socket.Close();
        }

        private void buttonMillOn_Click(object sender, EventArgs e)
        {
            try
            {
                byte[] sendBytes = BoardCMD.CMD_MILL_ON_SEND();
                boardControlPort.Write(sendBytes, 0, sendBytes.Length);
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }

        private void buttonMillOff_Click(object sender, EventArgs e)
        {
            try
            {
                byte[] sendBytes = BoardCMD.CMD_MILL_OFF_SEND();
                boardControlPort.Write(sendBytes, 0, sendBytes.Length);
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }


        public string ControlPortInitializeName()
        {
            string portName = "ERROR";
            try
            {
                string[] names = SerialPort.GetPortNames();
                foreach (string tmpName in names)
                {
                    SerialPort tmpPort = new SerialPort();
                    tmpPort = new SerialPort();
                    tmpPort.BaudRate = 9600;
                    tmpPort.PortName = tmpName;
                    tmpPort.ReadTimeout = 300;
                    try
                    {
                        tmpPort.Open();
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                    byte[] sendBytes = BoardCMD.CMD_BOARD_HANDSHAKE_SEND();
                    tmpPort.Write(sendBytes, 0, sendBytes.Length);
                    byte[] tmpReturnBytes = new byte[20];
                    for (int i = 0; (i < 150) && (tmpPort.BytesToRead < sendBytes.Length); i++)
                    {
                        Thread.Sleep(1);
                    }
                    if (tmpPort.BytesToRead > sendBytes.Length - 1)
                    {
                        tmpPort.Read(tmpReturnBytes, 0, tmpPort.BytesToRead);
                        int result = BoardCMD.BytesCompare(sendBytes, tmpReturnBytes, sendBytes.Length);
                        if (result == 0)
                        {
                            portName = tmpName;
                        }
                    }
                    tmpPort.Close();
                }
                return portName;
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
                return portName;
            }
        }
        /// <summary>
        /// 回到初始的接收状态
        /// </summary>
        void GotoReceiveStartState()
        {
            buffer[0] = 0;
            buffer[1] = 0;
            bufferPtr = 0;
            USB_READ_STATUS = READ_USB_START_STATUS;
        }
        /// <summary>
        /// 回到初始的接收状态并清空接收区，在接收错误的时候使用
        /// </summary>
        void ReveiveFlush()
        {
            GotoReceiveStartState();
            boardControlPort.ReadExisting();
        }
        //读取数据的状态
        const int READ_USB_START_STATUS = 0;
        const int READ_USB_DATA_STATUS = 1;
        int USB_READ_STATUS = READ_USB_START_STATUS;
        const int READ_PREFIX_STATUS = 0;
        const int READ_BOARD_DATA_STATUS = 4;

        byte[] buffer = new byte[500];
        int bufferPtr = 0;
        /// <summary>
        /// 接收线程，具体数据接收方式来源参见下位机板卡程序数据发送方式。
        /// </summary>
        private void ReceiveData()
        {
            while (true)
            {
                Thread.Sleep(1);
                try
                {
                StartState:
                    while (boardControlPort.BytesToRead > 0)
                    {
                        #region MyRegion
                        //this.boardControlPort.DataReceived -= (this.boardControlPort_DataReceived);
                        if (USB_READ_STATUS == READ_USB_START_STATUS)
                        {
                            if (boardControlPort.BytesToRead >= 4)
                            {
                                boardControlPort.Read(buffer, 0, 4);
                                bufferPtr=4;
                                UInt16 data_length = BitConverter.ToUInt16(buffer, 2);
                                if (buffer[0] != UltrasonicGlobal.ARTIFICIAL_BOARD_ADDR || data_length > UltrasonicGlobal.MAX_DATA_PACKAGE_SIZE)
                                {
                                    ReveiveFlush();
                                }
                                else
                                {
                                    USB_READ_STATUS = READ_USB_DATA_STATUS;
                                }
                            }
                        }
                        else if (USB_READ_STATUS == READ_USB_DATA_STATUS)
                        {
                            UInt16 data_length = BitConverter.ToUInt16(buffer, 2);
                            switch (buffer[1])
                            {
                                case UltrasonicGlobal.CMD_MILL_ON:
                                    if (boardControlPort.BytesToRead < 2) goto StartState;
                                    else if (data_length !=  4 + 2)
                                    {
                                        ReveiveFlush();
                                    }
                                    else
                                    {
                                        boardControlPort.Read(buffer, bufferPtr, 2);
                                        int crc = (int)BitConverter.ToUInt16(buffer, bufferPtr);
                                        int calCrc = CRC16.calcCrc16(buffer, 0, data_length - 2);
                                        if (crc != calCrc)
                                        {
                                            MessageBox.Show("打磨开启失败");
                                        }
                                        GotoReceiveStartState();
                                    }
                                    break;
                                case UltrasonicGlobal.CMD_MILL_OFF:
                                    if (boardControlPort.BytesToRead < 2) goto StartState;
                                    else if (data_length !=  4 + 2)
                                    {
                                        ReveiveFlush();
                                    }
                                    else
                                    {
                                        boardControlPort.Read(buffer, bufferPtr, 2);
                                        int crc = (int)BitConverter.ToUInt16(buffer, bufferPtr);
                                        int calCrc = CRC16.calcCrc16(buffer, 0, data_length - 2);
                                        if (crc!= calCrc)
                                        {
                                            MessageBox.Show("打磨关闭失败");
                                        }
                                        GotoReceiveStartState();
                                    }
                                    break;
                                default:
                                    GotoReceiveStartState();
                                    break;
                            }
                        }
                        #endregion
                    }
                }
                catch (Exception exc)
                {
                    if (!boardControlPort.IsOpen)
                    { return; }
                    MessageBox.Show(exc.Message);
                    //return;
                }
                finally
                {
                }
            }
        }

        private void buttonSetSpeed_Click(object sender, EventArgs e)
        {
            try
            {
                UltrasonicGlobal.SetWheelSpeed setSpeedStruct = new UltrasonicGlobal.SetWheelSpeed();
                setSpeedStruct.motor_type = UltrasonicGlobal.SMX_MOTOR_TYPE;
                setSpeedStruct.wheel_id = 1;
                setSpeedStruct.speed = Int16.Parse(textBoxSpeed.Text);
                byte[] sendBytes = BoardCMD.CMD_SET_WHEEL_SPEED_SEND(setSpeedStruct);
                boardControlPort.Write(sendBytes, 0, sendBytes.Length);
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }

        private void buttonSetPos_Click(object sender, EventArgs e)
        {
            try
            {
                UltrasonicGlobal.SetMotorPosition setPosStruct = new UltrasonicGlobal.SetMotorPosition();
                setPosStruct.motor_type = UltrasonicGlobal.SCSX_MOTOR_TYPE;
                setPosStruct.position = Int16.Parse(textBoxScsPos.Text); 
                setPosStruct.speed = Int16.Parse(textBoxScsSpe.Text);
                setPosStruct.motor_id = 1;
                setPosStruct.time = UInt16.Parse(textBoxScsTime.Text);
                byte[] sendBytes = BoardCMD.CMD_SET_MOTOR_POSITION_SEND(setPosStruct);
                boardControlPort.Write(sendBytes, 0, sendBytes.Length);
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }

        private void 连接验证ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (boardControlPort.IsOpen)
            {
                boardControlPort.Close();
            }
            string portName = ControlPortInitializeName();
            if (portName == "ERROR")
            {
                MessageBox.Show("板卡通信异常，请检查重试");
            }
            else
            {
                boardControlPort.BaudRate = 9600;
                boardControlPort.PortName = portName;
                boardControlPort.ReadTimeout = 800;
                boardControlPort.Open();
                threadReceive = new Thread(new ThreadStart(ReceiveData));
                threadReceive.IsBackground = true;
                threadReceive.Start();
                MessageBox.Show("板卡通信成功");
            }
        }

        private void 视频配置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Config cfg = new Config();
            cfg.ShowDialog();
        }

        private void wiFi连接ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                IPAddress ips = IPAddress.Parse(ControlIp.ToString());//("192.168.2.1");
                IPEndPoint ipe = new IPEndPoint(ips, Convert.ToInt32(Port.ToString()));//把ip和端口转化为IPEndPoint实例
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket
                socket.Bind(new IPEndPoint(IPAddress.Any, 2001));
                socket.Listen(2001);
                socket.Connect(ipe);//连接到服务器
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }

        private void tabPage1_SizeChanged(object sender, EventArgs e)
        {
            //pBShow.Top = (tabPage1.Height - pBShow.Height) / 2;
            //pBShow.Left = (tabPage1.Width - pBShow.Width) / 2;

            //btnEngineUp.Height = (tabPage1.Height - 150) / 3;
            //btnEngineDown.Height = (tabPage1.Height - 150) / 3;
            //btnEngineleft.Height = (tabPage1.Height - 150) / 3;
            //btnEngineright.Height = (tabPage1.Height - 150) / 3;

            //buttonLED.Height = (tabPage1.Height - 150) / 3;
            //buttonVideo.Height = (tabPage1.Height - 150) / 3;

            //buttonForward.Top = (btnEngineleft.Top + btnEngineleft.Bottom)/2;
            //buttonBackward.Top = (btnEngineleft.Top + btnEngineleft.Bottom) / 2;
               
            //btnEngineUp.Top = (tabPage1.Height - btnEngineUp.Height) / 2;
            //btnEngineDown.Top = (tabPage1.Height - btnEngineDown.Height) / 2;

            //buttonLED.Top = (btnEngineUp.Top*2 - btnEngineright.Top);
            //buttonVideo.Top = (btnEngineUp.Top * 2 - btnEngineright.Top);
        }

        private void buttonForward_MouseDown(object sender, MouseEventArgs e)
        {
            timerForward.Enabled = true;
        }

        private void buttonBackward_MouseDown(object sender, MouseEventArgs e)
        {
            timerBackward.Enabled = true;
        }

        private void buttonLeft_MouseDown(object sender, MouseEventArgs e)
        {
            timerLeft.Enabled = true;
        }

        private void buttonRight_MouseDown(object sender, MouseEventArgs e)
        {
            timerRight.Enabled = true;
        }

        private void buttonForward_MouseUp(object sender, MouseEventArgs e)
        {
            timerForward.Enabled = false;
            setWheelSameSpeed();
        }

        private void buttonBackward_MouseUp(object sender, MouseEventArgs e)
        {
            timerBackward.Enabled = false;
            setWheelSameSpeed();
        }

        private void buttonLeft_MouseUp(object sender, MouseEventArgs e)
        {
            timerLeft.Enabled = false;
            setWheelSameSpeed();
        }

        private void buttonRight_MouseUp(object sender, MouseEventArgs e)
        {
            timerRight.Enabled = false;
            setWheelSameSpeed();
        }

        private void timerForward_Tick(object sender, EventArgs e)
        {
            SetRobotAccelerate(LeftWheelId, MotorAccelerate, RightWheelId, MotorAccelerate);
        }

        private void timerBackward_Tick(object sender, EventArgs e)
        {
            SetRobotAccelerate(LeftWheelId, (Int16)(-1 * MotorAccelerate), RightWheelId, (Int16)(-1 * MotorAccelerate));
        }

        private void timerLeft_Tick(object sender, EventArgs e)
        {
            SetRobotAccelerate(LeftWheelId, (Int16)(-1 * MotorAccelerate), RightWheelId, MotorAccelerate);
        }

        private void timerRight_Tick(object sender, EventArgs e)
        {
            SetRobotAccelerate(LeftWheelId, MotorAccelerate, RightWheelId, (Int16)(-1 * MotorAccelerate));
        }

        private void setWheelSameSpeed()
        {
            try
            {
                byte[] sendBytes = BoardCMD.CMD_SET_WHEEL_SAME_SPEED_SEND();
                boardControlPort.Write(sendBytes, 0, sendBytes.Length);
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }
    }
}
